package com.heima.common.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.heima.common.util.LoginUserInfo;
import com.heima.common.util.UserInfoThreadLocal;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author SUMjane
 */
public class UserInfoInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1）拦截器->拦截所有请求->获取请求头中的userId
        String userId = request.getHeader("userId");

        //2）把userId存入ThreadLocal
        if(ObjectUtil.isNotEmpty(userId)){
            LoginUserInfo loginUserInfo = new LoginUserInfo();
            loginUserInfo.setId(Long.valueOf(userId));

            //3）Controller、Service、Dao->ThreadLocal.getUser()
            UserInfoThreadLocal.set(loginUserInfo);
        }
        // 修复：直接返回true，不需要调用父类方法
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoThreadLocal.remove();
    }
}
